<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\admin;

use App\Constants\ErrorCode;
use App\Controller\admin\common\Tree;
use App\Controller\admin\common\Util;
use App\Exception\BusinessException;
use App\Model\Admin\Admin;
use App\Model\Admin\AdminRole;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Http\Message\ResponseInterface;

use function Hyperf\Config\config;

class Crud extends Base
{
    /**
     * 查询.
     */
    public function select(): ResponseInterface
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput();
        $query = $this->doSelect($where, $field, $order);
        return $this->doFormat($query, $format, $limit);
    }

    /**
     * 添加.
     * @throws BusinessException
     */
    public function insert(): ResponseInterface
    {
        $request = $this->request;
        $data = $this->insertInput($request);
        $id = $this->doInsert($data);
        return $this->json(0, 'ok', ['id' => $id]);
    }

    /**
     * 更新.
     * @throws BusinessException
     */
    public function update(): ResponseInterface
    {
        $request = $this->request;
        [$id, $data] = $this->updateInput($request);
        $this->doUpdate($id, $data);
        return $this->json(0);
    }

    /**
     * 删除.
     * @throws BusinessException
     */
    public function delete()
    {
        $request = $this->request;
        $ids = $this->deleteInput($request);
        $this->doDelete($ids);
        return $this->json(0);
    }

    /**
     * 查询前置.
     * @throws BusinessException
     */
    protected function selectInput(): array
    {
        $request = $this->request;
        $field = $request->input('field', '');
        $order = $request->input('order', 'asc');
        $format = $request->input('format', 'normal');
        $limit = (int) $request->input('limit', $format === 'tree' ? 1000 : 10);
        $limit = $limit <= 0 ? 10 : $limit;
        $order = $order === 'asc' ? 'asc' : 'desc';
        $where = $request->all();
        $page = (int) $request->input('page');
        $page = $page > 0 ? $page : 1;
        $table = config('databases.default.prefix') . $this->model->getTable();
        $allow_column = $this->model->getConnection()->select("desc `{$table}`");
        if (! $allow_column) {
            throw new BusinessException(ErrorCode::SERVER_ERROR, '表不存在');
        }
        $allow_column = array_column((array) $allow_column, 'Field', 'Field');
        if (! in_array($field, $allow_column)) {
            $field = null;
        }

        foreach ($where as $column => $value) {
            if (
                $value === '' || ! isset($allow_column[$column])
                || is_array($value) && (empty($value) || ! in_array($value[0], ['null', 'not null']) && ! isset($value[1]))
            ) {
                unset($where[$column]);
            }
        }
        // 按照数据限制字段返回数据
        if (! (new common\Auth())->isSuperAdmin()) {
            if ($this->dataLimit === 'personal') {
                // 本人数据
                $where[$this->dataLimitField] = admin_id();
            } elseif ($this->dataLimit === 'auth') {
                // 本部门及以下数据
                $primary_key = $this->model->getKeyName();
                $table_name = $this->model->getTable();
                if ($table_name == config('databases.default.prefix') . 'dept') {
                    $dept_id = $this->request->input('id', '');
                    if ($dept_id) {
                        $where['id'] = $dept_id;
                    } else {
                        $where['id'] = ['in', (new common\Auth())->getScopeDeptIds(true)];
                    }
                } else {
                    if (! (new common\Auth())->isSuperAdmin() && (! isset($where[$primary_key]) || $this->dataLimitField != $primary_key)) {
                        // $where[$this->dataLimitField] = ['in', (new common\Auth)->getScopeAdminIds(true)];
                        $where[$this->dataLimitField] = ['in', (new common\Auth())->getScopeDeptAdminIds(true)];
                    }
                }
            } elseif ($this->dataLimit === 'role') {
                // 本部门的数据
                $admin = admin();
                $dept_id = $admin['dept_id'];
                // $role_ids = $admin['roles'];
                // $admin_ids = AdminRole::whereIn('role_id', $role_ids)->pluck('admin_id')->toArray();
                $admin_ids = Admin::where('dept_id', $dept_id)->pluck('id')->toArray();
                $where[$this->dataLimitField] = ['in', $admin_ids];
            }
        }
        return [$where, $format, $limit, $field, $order, $page];
    }

    /**
     * 指定查询where条件,并没有真正的查询数据库操作.
     */
    protected function doSelect(array $where, ?string $field = null, string $order = 'desc')
    {
        $model = $this->model;
        foreach ($where as $column => $value) {
            if (is_array($value)) {
                if ($value[0] === 'like' || $value[0] === 'not like') {
                    $model = $model->where($column, $value[0], "%{$value[1]}%");
                } elseif (in_array($value[0], ['>', '=', '<', '<>'])) {
                    $model = $model->where($column, $value[0], $value[1]);
                } elseif ($value[0] == 'in' && ! empty($value[1])) {
                    $valArr = $value[1];
                    if (is_string($value[1])) {
                        $valArr = explode(',', trim($value[1]));
                    }
                    $model = $model->whereIn($column, $valArr);
                } elseif ($value[0] == 'not in' && ! empty($value[1])) {
                    $valArr = $value[1];
                    if (is_string($value[1])) {
                        $valArr = explode(',', trim($value[1]));
                    }
                    $model = $model->whereNotIn($column, $valArr);
                } elseif ($value[0] == 'null') {
                    $model = $model->whereNull($column);
                } elseif ($value[0] == 'not null') {
                    $model = $model->whereNotNull($column);
                } elseif ($value[0] !== '' || $value[1] !== '') {
                    $model = $model->whereBetween($column, $value);
                }
            } else {
                $model = $model->where($column, $value);
            }
        }
        if ($field) {
            $model = $model->orderBy($field, $order);
        }
        return $model;
    }

    /**
     * 执行真正查询，并返回格式化数据.
     */
    protected function doFormat(mixed $query, mixed $format, mixed $limit): mixed
    {
        $methods = [
            'select' => 'formatSelect',
            'tree' => 'formatTree',
            'table_tree' => 'formatTableTree',
            'normal' => 'formatNormal',
        ];
        $paginator = $query->paginate($limit);
        $total = $paginator->total();
        $items = $paginator->items();
        if (method_exists($this, 'afterQuery')) {
            $items = call_user_func([$this, 'afterQuery'], $items);
        }
        $format_function = $methods[$format] ?? 'formatNormal';
        return call_user_func([$this, $format_function], $items, $total);
    }

    /**
     * 插入前置方法.
     * @throws BusinessException
     */
    protected function insertInput(RequestInterface $request): array
    {
        $session = $this->session;
        $data = $this->inputFilter($request->all());
        $password_filed = 'password';
        if (isset($data[$password_filed])) {
            $data[$password_filed] = Util::passwordHash($data[$password_filed]);
        }

        if (! (new common\Auth())->isSuperAdmin()) {
            if ($this->dataLimit === 'personal') {
                $data[$this->dataLimitField] = admin_id();
            } elseif ($this->dataLimit === 'auth') {
                if (! empty($data[$this->dataLimitField])) {
                    $admin_id = $data[$this->dataLimitField];
                    if (! in_array($admin_id, (new common\Auth())->getScopeAdminIds(true))) {
                        throw new BusinessException(ErrorCode::SERVER_ERROR, '无数据权限');
                    }
                }
                $data[$this->dataLimitField] = $session->get('admin.id');
            } elseif ($this->dataLimit === 'role') {
                if (empty($data[$this->dataLimitField])) {
                    $admin_id = admin_id();
                    $admin = admin();
                    $role_ids = $admin['roles'];
                    $admin_ids = AdminRole::whereIn('role_id', $role_ids)->pluck('admin_id')->toArray();
                    if (! in_array($admin_id, $admin_ids)) {
                        throw new BusinessException(ErrorCode::SERVER_ERROR, '无数据权限');
                    }
                    $data[$this->dataLimitField] = $admin_id;
                }
            }
        } elseif ($this->dataLimit && empty($data[$this->dataLimitField])) {
            $data[$this->dataLimitField] = admin_id();
        }
        return $data;
    }

    /**
     * 执行插入.
     * @return null|mixed
     */
    protected function doInsert(array $data)
    {
        $primary_key = $this->model->getKeyName();
        $model_class = get_class($this->model);
        $model = new $model_class();
        foreach ($data as $key => $val) {
            $model->{$key} = $val;
        }
        $model->save();
        return $primary_key ? $model->{$primary_key} : null;
    }

    /**
     * 更新前置方法.
     * @throws BusinessException
     */
    protected function updateInput(RequestInterface $request): array
    {
        $primary_key = $this->model->getKeyName();
        $id = $request->post($primary_key);
        $data = $this->inputFilter($request->post());
        $model = $this->model->find($id);
        if (! $model) {
            throw new BusinessException(ErrorCode::SERVER_ERROR, '记录不存在');
        }

        if (! (new common\Auth())->isSuperAdmin()) {
            if ($this->dataLimit == 'personal') {
                if ($model->{$this->dataLimitField} != admin_id()) {
                    throw new BusinessException(ErrorCode::SERVER_ERROR, '无数据权限');
                }
            } elseif ($this->dataLimit == 'auth') {
                $scopeAdminIds = (new common\Auth())->getScopeAdminIds(true);
                $admin_ids = [
                    $data[$this->dataLimitField] ?? false, // 检查要更新的数据admin_id是否是有权限的值
                    $model->{$this->dataLimitField} ?? false, // 检查要更新的记录的admin_id是否有权限
                ];
                foreach ($admin_ids as $admin_id) {
                    if ($admin_id && ! in_array($admin_id, $scopeAdminIds)) {
                        throw new BusinessException(ErrorCode::SERVER_ERROR, '无数据权限');
                    }
                }
            } elseif ($this->dataLimit === 'role') {
                $admin_id = admin_id();
                $admin = admin();
                $role_ids = $admin['roles'];
                $admin_ids = AdminRole::whereIn('role_id', $role_ids)->pluck('admin_id')->toArray();
                if (! in_array($admin_id, $admin_ids)) {
                    throw new BusinessException(ErrorCode::SERVER_ERROR, '无数据权限');
                }
            }
        }
        $password_filed = 'password';
        if (isset($data[$password_filed])) {
            // 密码为空，则不更新密码
            if ($data[$password_filed] === '') {
                unset($data[$password_filed]);
            } else {
                $data[$password_filed] = Util::passwordHash($data[$password_filed]);
            }
        }
        $data['updated_at'] = date('Y-m-d H:i:s');
        $data['updated_by'] = admin_id();
        unset($data[$primary_key]);
        return [$id, $data];
    }

    /**
     * 执行更新.
     */
    protected function doUpdate(mixed $id, mixed $data): void
    {
        $model = $this->model->find($id);
        foreach ($data as $key => $val) {
            $model->{$key} = $val;
        }
        $model->save();
    }

    /**
     * 对用户输入表单过滤.
     * @throws BusinessException
     */
    protected function inputFilter(array $data): array
    {
        $table = config('databases.default.prefix') . $this->model->getTable();
        $allow_column = $this->model->getConnection()->select("desc `{$table}`");
        if (! $allow_column) {
            throw new BusinessException(ErrorCode::SERVER_ERROR, '表不存在');
        }
        $columns = array_column($allow_column, 'Type', 'Field');
        foreach ($data as $col => $item) {
            if (! isset($columns[$col])) {
                unset($data[$col]);
                continue;
            }
            // 非字符串类型传空则为null
            if ($item === '' && ! str_contains(strtolower($columns[$col]), 'varchar') && strpos(strtolower($columns[$col]), 'text') === false) {
                $data[$col] = null;
            }
            if (is_array($item)) {
                $data[$col] = implode(',', $item);
            }
        }
        if (empty($data['created_at'])) {
            unset($data['created_at']);
        }
        if (empty($data['updated_at'])) {
            unset($data['updated_at']);
        }
        return $data;
    }

    /**
     * 删除前置方法.
     * @throws BusinessException
     */
    protected function deleteInput(RequestInterface $request): array
    {
        $primary_key = $this->model->getKeyName();
        if (! $primary_key) {
            throw new BusinessException(ErrorCode::SERVER_ERROR, '该表无主键，不支持删除');
        }
        $ids = (array) $request->post($primary_key, []);
        if (! (new common\Auth())->isSuperAdmin()) {
            $admin_ids = $this->model->where($primary_key, $ids)->pluck($this->dataLimitField)->toArray();
            if ($this->dataLimit == 'personal') {
                if (! in_array(admin_id(), $admin_ids)) {
                    throw new BusinessException(ErrorCode::SERVER_ERROR, '无数据权限');
                }
            } elseif ($this->dataLimit == 'auth') {
                if (array_diff($admin_ids, (new common\Auth())->getScopeAdminIds(true))) {
                    throw new BusinessException(ErrorCode::SERVER_ERROR, '无数据权限');
                }
            } elseif ($this->dataLimit === 'role') {
                if (! in_array(admin_id(), $admin_ids)) {
                    throw new BusinessException(ErrorCode::SERVER_ERROR, '无数据权限');
                }
            }
        }
        return $ids;
    }

    /**
     * 执行删除.
     */
    protected function doDelete(array $ids): void
    {
        if (! $ids) {
            return;
        }
        $primary_key = $this->model->getKeyName();
        $this->model->whereIn($primary_key, $ids)->each(function ($model) {
            $model->delete();
        });
    }

    /**
     * 格式化树.
     */
    protected function formatTree(mixed $items): ResponseInterface
    {
        $format_items = [];
        foreach ($items as $item) {
            $format_items[] = [
                'name' => $item->title ?? $item->name ?? $item->id,
                'value' => (string) $item->id,
                'id' => $item->id,
                'pid' => $item->pid,
            ];
        }
        $tree = new Tree($format_items);
        return $this->json(0, 'ok', $tree->getTree());
    }

    /**
     * 格式化表格树.
     */
    protected function formatTableTree(mixed $items): ResponseInterface
    {
        $tree = new Tree($items);
        return $this->json(0, 'ok', $tree->getTree());
    }

    /**
     * 格式化下拉列表.
     */
    protected function formatSelect(mixed $items): ResponseInterface
    {
        $formatted_items = [];
        foreach ($items as $item) {
            $formatted_items[] = [
                'name' => $item->title ?? $item->name ?? $item->id,
                'value' => $item->id,
            ];
        }
        return $this->json(0, 'ok', $formatted_items);
    }

    /**
     * 通用格式化.
     */
    protected function formatNormal(mixed $items, mixed $total): mixed
    {
        return $this->json(0, 'ok', $items, $total);
    }

    /**
     * 查询数据库后置方法，可用于修改数据.
     * @param mixed $items 原数据
     * @return mixed 修改后数据
     */
    protected function afterQuery(mixed $items): mixed
    {
        return $items;
    }
}
